﻿using System;
using System.IO;
using RayDen.Library.Core;
using RayDen.Library.Core.Primitives;
using RayDen.Library.Data;
using RayDen.Library.Data.Imaging;
using RayDen.Library.Entity.Frames;

namespace RayDen.RayEngine.Data
{
    public class ImportanceSampledInfiniteLight : BaseInfiniteLight
    {

        public const string InfiniteLightMapPath = "InfiniteLight.MapPath";


        public float shiftU, shiftV;
        private RgbSpectrum gain;
        public IEnvironmentMapSampler Sampler;

        public override string Name
        {
            get { return "Env_IS" + Sampler.Name; }
        }


        public ImportanceSampledInfiniteLight(RgbSpectrumTexture tx, RgbSpectrumTexture tx_l)
        {
            Sampler = new LatLongMap(tx, tx_l);

            shiftU = 0f;
            shiftV = 0f;
            gain = GlobalConfiguration.Instance.SpectralRendering ? RgbSpectrum.UnitSpectrum() : new RgbSpectrum(0.1f);
        }


        public ImportanceSampledInfiniteLight(FrameLightsource lightsource)
            :
            this(Load(lightsource.Parameters.Get<string>(InfiniteLightMapPath)), Load(GetTlFilename(lightsource.Parameters.Get<string>(InfiniteLightMapPath))))
        {

        }

        public ImportanceSampledInfiniteLight(string fileName)
            :
            this(Load(fileName), Load(GetTlFilename(fileName)))
        {

        }


        private static RgbSpectrumTexture Load(string fn)
        {
            if (string.IsNullOrWhiteSpace(fn))
                return null;
            if (Path.GetExtension(fn).NameContains("hdr", "exr"))
                return ImageFactory.FreeImageLoadExrBitmap(fn);
            return ImageFactory.FreeImageLoadBitmap(fn);
        }

        private static string GetTlFilename(string fileName)
        {
            var ext = Path.GetExtension(fileName);

            var fn = Path.GetFileNameWithoutExtension(fileName);
            var variants = new[]
                {
                    string.Format("{0}_env{1}", fn, ext),
                    string.Format("{0}_gi{1}", fn, ext),
                    string.Format("{0}_env{1}", fn.Substring(0, Math.Max(0,fn.Length-4)), ext),
                    string.Format("{0}_env{1}", fn.Substring(0, Math.Max(0,fn.Length-5)), ext),
                };
            foreach (var ltFile in variants)
            {
                var f = string.Format("{0}\\{1}", Path.GetDirectoryName(fileName), ltFile);
                if (File.Exists(f))
                    return f;
            }

            return string.Empty;
        }

        public void SetGain(RgbSpectrum g)
        {
            gain = g;
        }


        public void SetShift(float su, float sv)
        {
            shiftU = su;
            shiftV = sv;
        }


        public override ISpectrum Le(ref Vector dir)
        {
            throw new System.NotImplementedException();
        }
    }
}